﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	public class Main extends Sprite {
		//色宽
		private var colorWidth:Number = 1000000;
		private var colors:Array = new Array(0, 16777215);
		private var img:Sprite = new Sprite();
		private var bitmap:Bitmap;
		private var bitmapData:BitmapData;
		public function Main() {
			drawBg();
			img.addEventListener(MouseEvent.MOUSE_DOWN, sdrag);
			addChild(img);
			loadImg();
		}
		private function loadImg():void {
			var loader:Loader = new Loader();
			loader.load(new URLRequest("img.jpg"));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,setImg);
		}
		private function setImg(e:Event):void {
			var tw:Number = stage.stageWidth;
			var th:Number = stage.stageHeight;
			bitmapData = new BitmapData(tw, th, true, 0xffffffff);
			bitmapData.draw(e.target.content);
			bitmap = new Bitmap(filterWB(bitmapData));
			img.addChild(bitmap);
			//
			
		}
		private function drawBg():void {
			with (this.graphics) {
				beginFill(0xff0000);
				drawRect(0, 0, stage.stageWidth/2, stage.stageHeight);
				endFill();
			}
		}
		private function sdrag(e:MouseEvent):void {
			img.startDrag();
			stage.addEventListener(MouseEvent.MOUSE_UP, edrag);
		}
		private function edrag(e:MouseEvent):void {
			img.stopDrag();
			stage.removeEventListener(MouseEvent.MOUSE_UP, edrag);
		}
		private function filterWB(bitData:BitmapData):BitmapData {
			var _bitData:BitmapData = bitData.clone();
			var tw:Number = _bitData.width;
			var th:Number = _bitData.height;
			for (var w:Number = 0; w<tw; w++) {
				for (var h:Number = 0; h<th; h++) {
					var pixel:Number = _bitData.getPixel(w, h);
					for (var k:int = 0; k<colors.length; k++) {
						var t:Number = Math.abs(pixel - colors[k]);
						if (t<colorWidth) {
							var a:Number = t/colorWidth*255;
							var astr:String = a.toString(16);
							//trace(astr);
							var p32str:String = "0x"+astr+toColor(pixel.toString(16));
							var p32:Number = Number(p32str);
							_bitData.setPixel32(w, h, p32);
						}
					}
				}
			}
			return _bitData;
		}
		private function toColor(c:String):String{
			if(c.length == 6){
				return c;
			}
			var _c:String;
			var l:Number = Math.pow(10, 6-c.length);
			_c = l.toString().substring(1)+c;
			//trace(_c)
			return _c;
		}
	}
}